package com.qingkai.onlineshop.presentation.product

import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.material3.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.qingkai.onlineshop.app.Route
import com.qingkai.onlineshop.data.AppDatabase
import com.qingkai.onlineshop.presentation.dashboard.ProductItem
import com.qingkai.onlineshop.presentation.dashboard.testItemWithPics
import com.qingkai.onlineshop.ui.theme.OnLineShopAppTheme
import org.koin.androidx.compose.koinViewModel
import org.koin.core.parameter.parametersOf

/**
 *作者：created by 89270 on 2025/6/13 09:50
 *描述：
 */
@Composable
private fun injectPreviewModel(param: Route.Product): ProductViewModel {
    val context = LocalContext.current
    return remember { ProductViewModel(AppDatabase.getInstance(context = context), param) }
}


@Composable
fun ProductScreen(
    isPreview: Boolean = false,
    param: Route.Product,
    upPress: () -> Unit,
    navigateToRoute: (Route) -> Unit
) {
    val viewModel =
        if (isPreview) injectPreviewModel(param) else koinViewModel { parametersOf(param) }
    val state by viewModel.state.collectAsStateWithLifecycle()
    Scaffold(topBar = {
        ProductTopBar(title = param.title, backPress = { upPress.invoke() })
    }) { innerPadding ->
        LazyVerticalGrid(
            modifier = Modifier
                .fillMaxSize()
                .padding(innerPadding),
            columns = GridCells.Fixed(2)
        ) {
            items(if (isPreview) List(20) { testItemWithPics } else state.items) {
                ProductItem(
                    itemWithPics = it,
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(horizontal = 8.dp, vertical = 16.dp)
                        .clickable {
                            navigateToRoute(Route.Detail(it.item.id))
                        }
                )
            }
        }
    }

}

@Preview(showBackground = true)
@Composable
fun ProductScreenPreview() {
    OnLineShopAppTheme {
        ProductScreen(
            isPreview = true,
            param = Route.Product(0, "Cream"),
            upPress = {},
            navigateToRoute = {})
    }
}